Layouts let you position GUI elements next to each other. QVBoxLayout
for instance arranges items vertically:
The source code for this example is not much more complex than for our Hello World app. First, we import PyQt6:
from PyQt6.QtWidgets import *
Then, we create the required QApplication
:
app = QApplication([])
This time, we create a top-level window first. This will act as the container for the two buttons you see in the screenshot:
window = QWidget()
QWidget
is the most basic kind of widget. It would simply be empty if we didn't add any contents to it. (Kind of like a <div>
element in HTML.).
To tell Qt to arrange our buttons vertically, we create a QVBoxLayout
:
layout = QVBoxLayout()
Then, we add the two buttons to it:
layout.addWidget(QPushButton('Top'))
layout.addWidget(QPushButton('Bottom'))
Finally, we add the layout - and thus its contents - to the window
we created above:
window.setLayout(layout)
We conclude by showing the window and (as is required) handing control over to Qt:
window.show()
app.exec()
For instructions how you can run this example yourself, please see here.
The related QHBoxLayout
positions items horizontally. For an even more powerful approach, see QGridLayout
.